const express = require('express');
const server = express();
const bodyParser = require('body-parser');
const fs = require('fs');
const UUID = require('uuid');

server.use(bodyParser.json());
server.listen(2133, 'localhost');

server.post('/createFetchScript', (req, res) => {
    var content = '';
    content += `const fetch = require('node-fetch');
    const fs = require('fs');

    `;
    content += `var send = function (call) {\n`;
    content += `var json = {};\n`;
    content += `var a = `;
    content += req.body.a;
    content += '\n';
    content += `a.then(res => {
    if (res.status === 200) {
        var contentType = res.headers.get('content-type');
        let strings = contentType.split("; ");
        let type = strings[0];
        let charset = strings[1];
        if (type === 'application/json') {
            res.json().then(data => {
                json = JSON.stringify(data, null, '\\t');
                call(json);
                fs.writeFile('result.json', json, (err) => {
                    if (err) throw err;
                    console.log('文件已被保存');
                    return json;
                });
            });
        } 
        if (type === 'text/plain') {
            res.json().then(data => {
                json = JSON.stringify(data, null, '\\t');
                call(json);
                fs.writeFile('result.json', json, (err) => {
                    if (err) throw err;
                    console.log('文件已被保存');
                    return json;
                });
            });
        } 
        console.log("不支持的格式: " + res.headers.get('content-type'));
    } else {
        json = JSON.stringify({'status': res.status, 'statusText': res.statusText}, null, '\\t');
        call(json);
        fs.writeFile('result.json', json, (err) => {
                    if (err) throw err;
                    console.log('文件已被保存');
                    return json;
                });
    }
}).catch((err) => {
    console.log(err);
});`;
    content += '\n}';
    content += '\n';
    content += 'module.exports = {send}';

    var path = 'runtimejs/';
    var filename = UUID.v1();
    var fn = path + filename + '.js';
    fs.writeFile(fn, content, (err) => {
        if (err) throw err;
        console.log('fetch脚本文件已被保存');
        var send = require('./' + path + filename);
        send.send(data => {
            res.json(JSON.parse(data));
        });
    });
});
server.use('', express.static('./'));